<template>
    <span @click="openDialog">
        <slot></slot>
    </span>

    <mi-dialog v-model="showDialog" title="选择文件">
        <div class="file_container">
<!--            <div class="aside" v-loading="dir.loading">-->
<!--                <el-scrollbar>-->
<!--                    <el-menu class="dir_menu"-->
<!--                             :default-active="dir.selected"-->
<!--                             @select="dirSelect"-->
<!--                    >-->
<!--                        <el-menu-item index="">全部</el-menu-item>-->
<!--                        <el-menu-item v-for="li in dir.items" :index="li">-->
<!--                            <mi-icon name="fas fa-folder-open"></mi-icon>-->
<!--                            {{li}}-->
<!--                        </el-menu-item>-->

<!--                    </el-menu>-->
<!--                </el-scrollbar>-->

<!--            </div>-->
            <div class="main">
                <div class="header d_flex flex_jc_sb">
                    <el-space>


                        <!--                    <el-button>选择</el-button>-->

                        <el-upload :action="upload[type].url"
                                   :headers="upload.headers"
                                   :accept="upload[type].accept"
                                   :on-error="uploadError"
                                   :data="params"
                                   multiple
                                   :show-file-list="false"
                                   :http-request="customUpload"
                                   ref="uploadRef"
                        >
                            <el-button type="primary" icon="UploadFilled">上传</el-button>

                            <!--                        <template #tip>-->
                            <!--                            <el-alert v-if="data.error!=''" :title="data.error" type="error" :closable="false"/>-->
                            <!--                        </template>-->

                        </el-upload>

                    </el-space>
                        <el-button type="primary" @click="confirm">确认</el-button>
                    <el-space>

                    </el-space>
                </div>
                <div class="main_body">
                    <el-scrollbar>
                        <file-list :limit="limit" @selectChange="fileSelectChange" />
                    </el-scrollbar>
                </div>
            </div>
        </div>
    </mi-dialog>

</template>

<script setup lang="ts">

import {onBeforeMount, provide, reactive, ref} from "vue";
import FileList from "@/components/Form/MiUpload/FileList.vue";
import {msgError} from "@/utils/alert";
import {UploadFile, UploadFiles, UploadInstance, UploadRequestOptions} from "element-plus";
import {refreshToken, request, simplePost} from "@/utils/request";

const props = withDefaults(defineProps<{
    uploadUrl?: string
    type?: string,
    limit?:number,
    params?:Record<string, any>,
}>(), {
    uploadUrl:'',
    type:'image',
    limit:1,
})
const emits = defineEmits(['confirm'])

const showDialog = ref(false)
const uploadRef = ref<UploadInstance>()

const upload : Record<string, any> = reactive({
    headers: {},
    items:[],
    image:{
        url:import.meta.env.VITE_APP_UPLOAD_IMG_URL,
        accept: '.jpg,.jpeg,.png,.gif,.bmp,.JPG,.JPEG,.PBG,.GIF,.BMP',
    },
    video:{
        url: import.meta.env.VITE_APP_UPLOAD_VIDEO_URL,
        accept: '.avi,.wmv,.mpg,.mpeg,.mov,.rm,.ram,.swf,.flv,.mp4',
    },
    file:{
        url: import.meta.env.VITE_APP_UPLOAD_FILE_URL,
        accept: '',
    },
    selected: [],
    error: '',
})
// upload.headers['Authorization'] = "Bearer " + getToken(global.adminToken) // 让每个请求携带自定义token 请根据实际情况自行修改

// const dir: Record<string, any> = reactive({
//     loading: true,
//     items: [],
//     selected: ''
// })

const file: Record<string, any> = reactive({
    loading: true,
    items: [],
    selected:[],
    page:1
})

const openDialog = () => {
    showDialog.value = true
}

// const getDirs = () => {
//     dir.loading = true
//     simpleGet('/index.upload/dirs').then(({items}) => {
//         dir.items = items
//         dir.loading = false
//     })
// }



// const dirSelect = (index:string) => {
//     dir.selected = index
//     file.selected = []
//     getFiles(index, '')
// }


const fileSelectChange = (files: any[]) => {
    file.selected = files
}

const confirm = () => {
    emits("confirm", file.selected)
    showDialog.value = false
}

// 使用自定义上传方式
const customUpload = (options: UploadRequestOptions) => {

    console.log("options", options)

    const formData = new FormData()
    formData.append("file", options.file)
    for (const k in options.data){
        formData.append(k, options.data[k] as string)
    }
    request.post(options.action, formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }).then(res => {
        const {data} = res
        const {error} = data
        if (error == 0){
            // emits("update:modelValue", res.url)
            file.items.unshift(data.file)
            upload.error = ''    // 清空错误信息
        }else{
            msgError(data.msg)
            upload.error = data.msg
        }

    }).catch(e => {
        msgError(e)
    })


}

const uploadError = (res:any) => {
    msgError("上传失败")
    upload.error = "上传失败"
}


onBeforeMount(() => {
    // getDirs()
    // getFiles('', '')
})

provide('file', file)


</script>

<style scoped lang="scss">
.file_container {
    height: 100%;
    display: flex;
    //background-color: #fff;
    .aside {
        height: 100%;
        width: 130px;
        flex-shrink: 0;
        overflow: hidden;

        .dir_menu {
            width: 100%;
            overflow: hidden;
        }
    }

    .main {
        flex: 1;
        display: flex;
        flex-direction: column;
        height: 100%;
        padding-left: 15px;

        .header {
            height: 32px;
            margin-bottom: 15px;
            flex-shrink: 0;
            //background-color: #fff;
        }

        .body {
            flex: 1;
        }
    }
}

</style>
